<template>
  <div>
    <el-dialog
      :title="dataModel._id ? '修改数据' : '添加数据'"
      :visible.sync="dialogVisible"
      destroy-on-close
      :width="`${popWidth}px`">
      <div>
        <el-form label-width="80px">
          <el-form-item label="排序索引">
            <el-input-number v-model="dataModel.index" :min="0" :max="1000" label="排序索引"></el-input-number>
          </el-form-item>
        </el-form>
        <slot />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="okBtnClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
  import { Vue, Component, Prop } from 'vue-property-decorator'
  import DataModel from '@/models/DataModel'
  import YBPopView from "@/utils/popView";
  import {JsonEditerType} from "@/components/global/jsoneditor/types";

  @Component({
    components: {
    }
  })
  export default class ComArrayDataAddPop extends Vue {

    @Prop({ type: Number, default: 600 }) popWidth!: number
    @Prop({ type: Function }) getDataFun!: Function

    dialogVisible = false
    loading = false
    dataModel = new DataModel()

    show(dataModel?: DataModel) {
      this.dataModel = new DataModel()
      if (dataModel) {
        this.dataModel.setDataWithJson(dataModel);
      } else {
        this.dataModel.superId = this.$route.params.id
      }
      this.dialogVisible = true
      this.loading = false
    }

    okBtnClick() {
      this.loading = true
      const resData = this.getDataFun()
      if (resData instanceof Promise) {
        resData.then((data: unknown) => {
          this.dataModel.setData(data)
          this.saveData()
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.dataModel.setData(resData)
        this.saveData()
      }
    }

    saveData() {
      if (this.dataModel._id) {
        this.dataModel.updateDataArr().then(() => {
          YBPopView.msgSuccess('更新成功')
          this.dialogVisible = false
          this.$emit('success')
        })
      } else {
        this.dataModel.addArrayData().then(() => {
          YBPopView.msgSuccess('添加成功')
          this.dialogVisible = false
          this.$emit('success')
        })
      }
    }
  }
</script>

<style scoped>

</style>
